package com.project.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.project.bean.OrderBean;
import com.project.vo.Infos;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyl
 * description:
 */
@Component
public class RedisGetUtil {
    @Resource
    RedisCacheUtil redisCacheUtil;

    /**
     * 获取redis中对应的订单
     *
     * @return
     */
    public List<OrderBean> getOrderList(String CodeAndStatue) {

        Boolean flag = redisCacheUtil.hasKey(CodeAndStatue);
        if (flag) {
            Object object = redisCacheUtil.get(CodeAndStatue);
            String txt = JSONArray.toJSONString(object);
            List<OrderBean> list = JSON.parseArray(txt, OrderBean.class);
            return list;
        }
        return null;
    }

    /**
     * 添加订单对象至相应的redis中
     *
     * @param CodeAndStatue
     * @param orderBean
     * @return
     */
    public Infos addRedisOrder(String CodeAndStatue, OrderBean orderBean) {
        List<OrderBean> list = getOrderList(CodeAndStatue);
        //如果该骑手redis下没有订单集合则对骑手的订单进行一个新建
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(orderBean);
        boolean flag = redisCacheUtil.set(CodeAndStatue, list);
        if (flag) {
            return new Infos(1, "添加至redis成功");
        }
        return new Infos(0, "添加至redis失败");
    }

    /**
     * 删除订单对象至相应的redis中
     *
     * @param CodeAndStatue
     * @param code
     * @return
     */
    public Infos delRedisOrder(String CodeAndStatue, String code) {
        List<OrderBean> list = getOrderList(CodeAndStatue);
        OrderBean orderBean = new OrderBean();
        for (OrderBean bean : list) {
            if (bean.getCode().equals(code)) {
                orderBean = bean;
                break;
            }
        }
        list.remove(orderBean);
        //更新
        boolean flag = redisCacheUtil.set(CodeAndStatue, list);
        if (flag) {
            return new Infos(1, "从redis中移除成功");
        }
        return new Infos(0, "从redis中移除失败");
    }
}
